package com.icss.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.icss.model.Item;
import com.icss.model.ItemCategory;
import com.icss.service.ItemService;
import com.icss.util.MyUtil;

@Controller
@RequestMapping("item")
public class ItemController {
	@Autowired
	ItemService is;
	//商品管理首页
	@RequestMapping("item")
	public String item(Model model,@RequestParam(value="current",defaultValue="1")int current) {
		List<Item> listAll = is.findAll();
		int totalPage=0;//总页数
		int pageSize=5;//每页显示的记录数
		if(listAll.size()%pageSize==0) {
			totalPage=listAll.size()/pageSize;
		}else {
			totalPage=listAll.size()/pageSize+1;
		}
		int startIndex = 0;
		startIndex = (current-1)*pageSize;
		Map<String, Integer> map=new HashMap<String,Integer>();
		map.put("start", startIndex);
		map.put("pageSize", pageSize);
		List<Item> findPage = is.findByPage(map);
		model.addAttribute("fruit", findPage);
		model.addAttribute("totalPage",totalPage);
		model.addAttribute("current",current);
		return "item/item";
	}
	//商品管理增加
	@RequestMapping("add")
	public String add(Map<String, Object>map) {
		List<ItemCategory> findAll = is.findAllCate();
		map.put("lb", findAll);
		return "item/add";
	}
	@RequestMapping("toAdd")
	public String toAdd(Item i,MultipartFile mfile,HttpServletRequest request) {
		//获取绝对路径
		String realPath = request.getServletContext().getRealPath("image");
		System.out.println(realPath);
		//获取图片名字
		String originalFilename = MyUtil.getStringID()+mfile.getOriginalFilename();
		//创建file
		File file = new File(realPath+"//"+originalFilename);
		System.out.println(file);
		//文件上传
		try {
			mfile.transferTo(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		i.setUrl1(originalFilename);
		boolean add = is.add(i);
		if(add) {
			return "redirect:/item/item";
		}else {
			return "item/add";
		}
	}
	
	
}
